package com.smartsofa.main;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.smartsofa.R;
import com.smartsofa.util.AsyncImageLoader;
import com.smartsofa.util.MyUtils;
import com.smartsofa.util.Tools;

public class FamilyInfo extends Activity {

	private Button bt_back;
	private ImageView family_img;
	private EditText family_name;
	private EditText family_sign;
	private Button bt_submit;
	private TextView tv_createtime;
	private TextView tv_adminuser;
	private TextView tv_member_num;
	private String[] items = new String[] { "选择本地图片", "拍照" };

	private Intent intent;
	private int familyId;
	private String photostr;

	private ProgressDialog mDialog;
	private ProgressDialog mDialog2;
	private String url;
	private Boolean flag = false;
	private String reg_msg;
	private JSONObject json;
	private JSONObject jsonobj;
	// 定义网络连接超时判定变量
	private boolean network_timeout = false;
	/* 请求码 */
	private static final int IMAGE_REQUEST_CODE = 0;
	private static final int CAMERA_REQUEST_CODE = 1;
	private static final int RESULT_REQUEST_CODE = 2;
	private static String path="/sdcard/myInformation/";
	private static final String IMAGE_FILE_NAME = "family_img.jpg";
	private boolean flag_family_img=false;
	private Bitmap original_bitmap ;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.detail_familyinfo);
		Bundle bundle = getIntent().getExtras();
		familyId = Integer.valueOf(bundle.getString("familyId"));
		initView();
	}

	private void initView() {
		family_name = (EditText) findViewById(R.id.et_family_name);
		family_sign = (EditText) findViewById(R.id.et_family_sign);
		bt_back = (Button) findViewById(R.id.back);
		bt_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				FamilyInfo.this.finish();
			}
		});
		bt_submit = (Button) findViewById(R.id.bt_submit);
		tv_createtime = (TextView) findViewById(R.id.tv_createtime);
		tv_adminuser = (TextView) findViewById(R.id.tv_adminuser);
		tv_member_num = (TextView) findViewById(R.id.tv_member_num);
		family_img=(ImageView)findViewById(R.id.detail_family_img);
		family_img.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showDialog();				
			}
		});
		mDialog = new ProgressDialog(FamilyInfo.this);
		mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		mDialog.setMessage("加载中，请稍候...");
		mDialog.show();
		Thread getData = new Thread(new getFamilyInfo(familyId));
		getData.start();
		bt_submit.setOnClickListener(new updateFamilyInfo());
		
	}

	private void showDialog() {

		new AlertDialog.Builder(this)
				.setTitle("设置头像")
				.setItems(items, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case 0:
							Intent intentFromGallery = new Intent();
							intentFromGallery.setType("image/*"); // 设置文件类型
							intentFromGallery
									.setAction(Intent.ACTION_GET_CONTENT);
							startActivityForResult(intentFromGallery,
									IMAGE_REQUEST_CODE);
							
							break;
						case 1:

							Intent intentFromCapture = new Intent(
									MediaStore.ACTION_IMAGE_CAPTURE);
							// 判断存储卡是否可以用，可用进行存储
							if (Tools.hasSdcard()) {

								intentFromCapture.putExtra(
										MediaStore.EXTRA_OUTPUT,
										Uri.fromFile(new File(Environment
												.getExternalStorageDirectory(),
												IMAGE_FILE_NAME)));
							}

							startActivityForResult(intentFromCapture,
									CAMERA_REQUEST_CODE);
							break;
						}
					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				}).show();

	}
	class updateFamilyInfo implements OnClickListener {

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			try {
				//原始信息
				String familyName = jsonobj.getString("familyName").toString();
				String familySign = jsonobj.getString("signature").toString();
				//修改后的信息
				String u_familyName=family_name.getText().toString().trim();
				String u_familySign=family_sign.getText().toString().trim();
				// 判断信息是否修改过
				if(u_familyName.equals("")
						|| u_familySign.equals("")) {
					Toast.makeText(FamilyInfo.this, "信息不能为空！",
							Toast.LENGTH_SHORT).show();
				} else if (u_familyName.equals(familyName)
						&& u_familySign.equals(familySign)) {
					Toast.makeText(FamilyInfo.this, "您还没有修改过信息！",
							Toast.LENGTH_SHORT).show();
				} else {
					Thread thread = new Thread(new updateFamilyInfo_thread(u_familyName,u_familySign));
					thread.start();
					mDialog2 = new ProgressDialog(FamilyInfo.this);
					mDialog2.requestWindowFeature(Window.FEATURE_NO_TITLE);
					mDialog2.setMessage("处理中，请稍候...");
					mDialog2.show();
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	class updateFamilyInfo_thread implements Runnable {

		String familyName;
		String familySign;
		public updateFamilyInfo_thread(String familyName,String familySign){
			this.familyName=familyName;
			this.familySign=familySign;
		}
		@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					url=MyUtils.getUrl()+"family_updateFamily?userid="+MyUtils.getUSERID()+"&familyid="+familyId+"&familyname="+familyName+"&signature="+familySign;
					HttpGet request = new HttpGet(url);																
					BasicHttpParams httpParams = new BasicHttpParams();
					HttpConnectionParams.setConnectionTimeout(httpParams,MyUtils.REQUEST_TIMEOUT);
				    HttpClient httpClient = new DefaultHttpClient(httpParams);
		            HttpResponse httpResponse = httpClient.execute(request);					       
			       	
			      if (httpResponse.getStatusLine().getStatusCode() == 200) {
			    	  network_timeout=true;
			          String jsonString = EntityUtils.toString(httpResponse.getEntity());
			          json = new JSONObject(jsonString);
			          flag=json.getBoolean("success");
			          reg_msg=json.getString("msg");
			          Message msg = updateFamilyInfo_handler.obtainMessage();
						if(network_timeout){
							if (flag) {				
								msg.what = 1;
								
							}else{
								msg.what = 2;			
							}
						}			
						else{
							msg.what = 3;						
						}
						updateFamilyInfo_handler.sendMessage(msg);			         
			      }
			      }catch (Exception e) {
			        	 e.printStackTrace();
			     }
			}
	}

	Handler updateFamilyInfo_handler = new Handler() {
		public void handleMessage(Message msg) {
			mDialog2.dismiss();
			switch (msg.what) {
			case 1:
				Toast.makeText(FamilyInfo.this, "家庭组信息已更新！",
						Toast.LENGTH_SHORT).show();
				break;
			case 2:
				Toast.makeText(FamilyInfo.this, reg_msg.toString(),
						Toast.LENGTH_SHORT).show();
				break;
			case 3:
				Toast.makeText(FamilyInfo.this, "网络连接超时!", Toast.LENGTH_SHORT)
						.show();
				break;
			}
		}
	};
	class getFamilyInfo implements Runnable {
		int familyId;

		public getFamilyInfo(int familyId) {
			this.familyId = familyId;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				url = MyUtils.getUrl() + "family_displayFamily?familyid="
						+ familyId;
				HttpGet request = new HttpGet(url);
				BasicHttpParams httpParams = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParams,
						MyUtils.REQUEST_TIMEOUT);
				HttpClient httpClient = new DefaultHttpClient(httpParams);
				HttpResponse httpResponse = httpClient.execute(request);

				if (httpResponse.getStatusLine().getStatusCode() == 200) {
					network_timeout = true;
					String jsonString = EntityUtils.toString(httpResponse
							.getEntity());
					json = new JSONObject(jsonString);
					flag = json.getBoolean("success");
					reg_msg = json.getString("msg");
					Message msg = content_handler.obtainMessage();
					if (network_timeout) {
						if (flag) {
							msg.what = 1;

						} else {
							msg.what = 2;
						}
					} else {
						msg.what = 3;
					}
					content_handler.sendMessage(msg);

				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		Handler content_handler = new Handler() {
			public void handleMessage(Message msg) {
				mDialog.dismiss();
				switch (msg.what) {
				case 1:
					try {
						jsonobj = json.getJSONObject("obj");
						family_name.setText(jsonobj.getString("familyName"));
						family_sign.setText(jsonobj.getString("signature"));
						tv_createtime.setText(jsonobj.getString("createTime"));
						tv_adminuser.setText(jsonobj.getString("adminName"));
						tv_member_num.setText(jsonobj.getString("memberNum"));
						String familyImg=jsonobj.getString("familyImg");
						if(!jsonobj.getString("familyImg").equals("")){
							AsyncImageLoader imageLoader=new AsyncImageLoader(getApplicationContext());
							Bitmap bitmap = imageLoader.loadImage(family_img, familyImg);
			 				if (bitmap != null) {
			 					family_img.setImageBitmap(bitmap);
			 				}
						}						
						if(Integer.valueOf(jsonobj.getString("adminid"))!=MyUtils.getUSERID()){
							bt_submit.setVisibility(View.INVISIBLE);
							family_name.setKeyListener(null);
							family_sign.setKeyListener(null);
							family_img.setClickable(false);
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					break;
				case 2:
					Toast.makeText(FamilyInfo.this, reg_msg.toString(),
							Toast.LENGTH_SHORT).show();
					break;
				case 3:
					Toast.makeText(FamilyInfo.this, "网络连接超时!",
							Toast.LENGTH_SHORT).show();
					break;
				}
			}
		};

	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		//结果码不等于取消时候
		if (resultCode != RESULT_CANCELED) {
			switch (requestCode) {
			case IMAGE_REQUEST_CODE:
				startPhotoZoom(data.getData());
				break;
			case CAMERA_REQUEST_CODE:
				if (Tools.hasSdcard()) {
					File tempFile = new File(
							Environment.getExternalStorageDirectory()
									,IMAGE_FILE_NAME);
					startPhotoZoom(Uri.fromFile(tempFile));
				} else {
					Toast.makeText(getApplicationContext(), "未找到存储卡，无法存储照片！",
							Toast.LENGTH_LONG).show();
				}
				break;
			case RESULT_REQUEST_CODE:
				if (data != null) {
					getImageToView(data);
				}
				break;
			}
		}
	}
	public void startPhotoZoom(Uri uri) {

		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 设置裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 200);
		intent.putExtra("outputY", 200);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, 2);
	}

	/**
	 * 保存裁剪之后的图片数据
	 * 
	 * @param picdata
	 */
	private void getImageToView(Intent data) {
		Bundle extras = data.getExtras();
		if (extras != null) {
			Bitmap photo = extras.getParcelable("data");
			photostr=convertIconToString(photo);
			family_img.setImageBitmap(photo);
			
			/**
			 * 将图片上传至服务器端
			 */
		    Thread thread = new Thread(new sendPicToServer());
		    thread.start();
		}
	}
	 public static String convertIconToString(Bitmap bitmap)  
	 {  
	     ByteArrayOutputStream baos = new ByteArrayOutputStream();// outputstream  
	     bitmap.compress(CompressFormat.PNG, 100, baos);  
	     byte[] appicon = baos.toByteArray();// 转为byte数组  
	     return Base64.encodeToString(appicon, Base64.DEFAULT);  
	 }
	 class sendPicToServer implements Runnable{
		 
		 @Override
		 public void run() {	
			 String urlString =MyUtils.getUrl()+"img_uploadFamily"; 
			 HttpPost post;
			try {
				post = new HttpPost(new URI(urlString));
				JSONObject json = new JSONObject();
			
				json.put("fileData",photostr);	
				json.put("familyId", familyId);			
				post.setEntity(new StringEntity(json.toString(),"utf-8"));
				BasicHttpParams httpParams = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParams,3000);
				HttpClient httpClient = new DefaultHttpClient(httpParams);
				HttpResponse httpResponse = httpClient.execute(post);
				if (httpResponse.getStatusLine().getStatusCode() == 200) {
					HttpEntity entity = httpResponse.getEntity();
					Log.i("send png to server", "success!");
					if (entity != null) {
						// 获取服务器响应的json字符串
						String jsonobj = EntityUtils.toString(entity);
					    Log.i("jsonobjfamilyimage", jsonobj);	
						JSONObject jsonObject = new JSONObject(jsonobj);
					    int flag=jsonObject.getInt("flag");
					    String imagefileString = Environment
								.getExternalStorageDirectory()
								+ "/family_img.jpg";
						File file = new File(
								imagefileString);
						if(file.exists()){
							file.delete();
							Log.i("删除家庭组图片", "success");
						}			
					}
				}		
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (URISyntaxException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
		
		 }
	 }
}
	
